package com.supreme.nettyapp.generalserver.pingserver.handler;

import io.netty.channel.*;
import io.netty.handler.codec.mqtt.MqttFixedHeader;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageType;
import io.netty.handler.codec.mqtt.MqttQoS;

public class PingServerHandler extends SimpleChannelInboundHandler<MqttMessage> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelActive");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelInactive");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MqttMessage mqttMessage) throws Exception {
        switch (mqttMessage.fixedHeader().messageType()) {
            case PINGREQ:
                this.handlePingReqMessage(ctx.channel());
                break;
        }
    }

    private void handlePingReqMessage(Channel channel) {
        MqttFixedHeader fixedHeader = new MqttFixedHeader(
                MqttMessageType.PINGRESP,
                false,
                MqttQoS.AT_MOST_ONCE,
                false,
                0);
        MqttMessage mqttMessage = new MqttMessage(fixedHeader);
        channel.writeAndFlush(mqttMessage);
    }
}
